﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.ExternalProcessingRecord.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.ExternalProcessingRecord
{
    public class ExternalProcessingRecordService : BPMReportPlatformAppService, IExternalProcessingRecordService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bpmUtilsApp;
        private readonly IBPMPlatformAppService _iBpmPlatformApp;
        private char[] splitChat = new char[] { ',', ';', '，', '；' };
        public ExternalProcessingRecordService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bpmUtilsApp
            , IBPMPlatformAppService iBpmPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bpmUtilsApp = bpmUtilsApp;
            _iBpmPlatformApp = iBpmPlatformApp;
        }

        public async Task<PagedResultDto<GetExternalProcessingRecordOutput>> GetAllAsync(
            GetExternalProcessingRecordInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBpmPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bpmUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetExternalProcessingRecordOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetExternalProcessingRecordOutput>> ExportAsync(GetExternalProcessingRecordInput input)
        {
            var listQueryable = GetQueryableByExport(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        private ISugarQueryable<GetExternalProcessingRecordOutput> GetQueryable(GetExternalProcessingRecordInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<ExternalProcessingRecordHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId)
                )
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                 .WhereIF(!string.IsNullOrWhiteSpace(input.Factory),
                    x => input.Factory.Split(splitChat, StringSplitOptions.RemoveEmptyEntries).ToArray().Contains(x.Factory))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, b) => new GetExternalProcessingRecordOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    ProcessStartTime = x.AddTime,
                    ProcessStartUserName = x.AddUserName,
                    OrderStatus = b.ProcessStatusName,
                    Factory = x.Factory,
                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);
            return listQueryable;
        }


        private ISugarQueryable<GetExternalProcessingRecordOutput> GetQueryableByExport(GetExternalProcessingRecordInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<ExternalProcessingRecordDetail, ExternalProcessingRecordHeader, BusinessProcessesNew>(
                (a, b, c) => new JoinQueryInfos(JoinType.Left, a.InstanceNumber == b.InstanceNumber, JoinType.Left, b.InstanceNumber == c.InstanceId))
                .WhereIF(!input.IsQueryAll, (a, b, c) => b.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (a, b, c) => b.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (a, b, c) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), c.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), (a, b, c) => b.AddUserName.Contains(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Factory),
                    (a, b, c) => input.Factory.Split(splitChat, StringSplitOptions.RemoveEmptyEntries).ToArray().Contains(b.Factory))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (a, b, c) => b.AddTime >= input.StartCreationTime && b.AddTime <= input.EndCreationTime)
                .Select((a, b, c) => new GetExternalProcessingRecordOutput()
                {
                    InstanceNumber = a.InstanceNumber,
                    ProcessStartTime = b.AddTime,
                    ProcessStartUserName = b.AddUserName,
                    OrderStatus = c.ProcessStatusName,
                    Factory = b.Factory,
                    Customer = a.Customer,
                    EnterMaterial = a.EnterMaterial,
                    OrderDate = a.OrderDate,
                    OrderVolume = a.OrderVolume,
                    ProductName = a.ProductName,
                    Remark = a.Remark,
                    RequestedDeliveryDate = a.RequestedDeliveryDate,
                    Salesman = a.Salesman,
                    SpecificReason = a.SpecificReason,
                    TransferClassificationReason = a.TransferClassificationReason,
                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);
            return listQueryable;
        }
    }
}